package cn.lei.netty.herostory;

import cn.lei.netty.herostory.model.UserManager;
import cn.lei.netty.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义消息处理器
 *
 * @author lil
 */
public class GameMsgHandler extends SimpleChannelInboundHandler<Object> {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(GameMsgHandler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        if (ctx == null) {
            return;
        }

        try {
            super.channelActive(ctx);
            BroadCaster.addChannel(ctx.channel());
        } catch (Exception ex) {
            //记录错误日志
            LOGGER.error(ex.getMessage(), ex);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        if (ctx == null) {
            return;
        }

        try {
            super.handlerRemoved(ctx);
            BroadCaster.removeChannel(ctx.channel());

            Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

            if (userId == null) {
                return;
            }
            LOGGER.info("用户准备离场...");
            //用户离场
            UserManager.removeByUserId(userId);


            GameMsgProtocol.UserQuitResult.Builder userQuitBuilder = GameMsgProtocol.UserQuitResult.newBuilder();
            userQuitBuilder.setQuitUserId(userId);

            //构建结果并广播
            GameMsgProtocol.UserQuitResult newResult = userQuitBuilder.build();
            BroadCaster.broadcast(newResult);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }


    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (ctx == null || msg == null) {
            return;
        }
        MainMsgProcessor.getInstance().process(ctx, msg);
    }

}
